package quota

import (
	dbModel "ZHONGYIHANGYAN/bean/dbModel"
	"ZHONGYIHANGYAN/bean/request"
	"ZHONGYIHANGYAN/bean/response"
	"fmt"
	"strings"
)

// 获取指标列表
func (manage *QuotaManage) GetQuotaList(query *request.GetQuotaListQuery) ([]response.GetQuotaListResponseInfo, error) {
	db := manage.DataBase.DB()
	tx := db.Model(&dbModel.Quota{})
	if query.TemplateId != "" {
		tx = tx.Where("template_id = ?", query.TemplateId)
	}
	if query.Name != "" {
		tx = tx.Where("name like ?", "%"+query.Name+"%")
	}
	tx.Order("id ASC")

	var quotas []dbModel.Quota
	if err := tx.Find(&quotas).Error; err != nil {
		// 如果发生错误，返回nil和具体的错误信息
		return nil, err
	}

	// 转换数据格式并处理换行符
	quotaList := make([]response.GetQuotaListResponseInfo, len(quotas))
	for i, quota := range quotas {
		// 处理 EvaluationScore 从 *int 到 int 的转换
		evaluationScore := 0
		if quota.EvaluationScore != nil {
			evaluationScore = *quota.EvaluationScore
		}

		// 处理 EvaluationCriteria 中的换行符，确保前端能正确显示
		evaluationCriteria := quota.EvaluationCriteria
		// 如果数据库中的换行符被转义了，需要还原
		if strings.Contains(evaluationCriteria, "\\n") {
			evaluationCriteria = strings.ReplaceAll(evaluationCriteria, "\\n", "\n")
		}

		quotaList[i] = response.GetQuotaListResponseInfo{
			Id:                 quota.Id,
			Name:               quota.Name,
			Level:              quota.Level,
			EvaluationCriteria: evaluationCriteria,
			EvaluationLevel:    quota.EvaluationLevel,
			EvaluationScore:    evaluationScore,
			Note:               quota.Note,
			TemplateId:         quota.TemplateId,
		}
	}

	return quotaList, nil
}

// 添加、修改指标列表
func (manage *QuotaManage) AddOrUpdateQuota(info *dbModel.Quota) error {
	db := manage.DataBase.DB()
	result := db.Save(&info)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		if info.Id != "" {
			return fmt.Errorf("更新指标失败：ID 为 %s 的记录未找到", info.Id)
		} else {
			return fmt.Errorf("添加指标失败")
		}
	}
	return nil
}

// 删除指标列表
func (manage *QuotaManage) DeleteQuota(quotaIds []string) error {
	if len(quotaIds) == 0 {
		return nil
	}

	db := manage.DataBase.DB()
	result := db.Where("id IN ?", quotaIds).Delete(&dbModel.Quota{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("没有找到要删除的记录，ID列表可能无效或记录已被删除")
	}
	return nil
}
